<template>
  <div class="live-room-view">
    <div v-if="loading" class="loading-container">
      <el-spinner size="large" />
      <p>正在加载直播间...</p>
    </div>
    
    <template v-else-if="liveRoom">
      <!-- 直播播放器区域 -->
      <div class="live-player-section">
        <div class="live-player">
          <video 
            ref="videoPlayer" 
            class="live-video"
            :poster="liveRoom.cover"
            autoplay 
            muted 
            playsinline
          >
            <source :src="liveStreamUrl" type="application/x-mpegURL" />
          </video>
          
          <!-- 直播信息覆盖层 -->
          <div class="live-overlay">
            <div class="live-status">
              <span v-if="liveRoom.status === 'live'" class="live-badge">
                <span class="live-dot"></span>
                直播中
              </span>
              <span v-else class="offline-badge">已结束</span>
            </div>
            <div class="viewer-stats">
              <i class="el-icon-user"></i>
              <span>{{ formatViewerCount(liveRoom.viewers) }}</span>
            </div>
          </div>
        </div>
        
        <!-- 直播间信息 -->
        <div class="live-info-section">
          <h1 class="live-title">{{ liveRoom.title }}</h1>
          
          <div class="streamer-info">
            <img :src="liveRoom.streamer.avatar" :alt="liveRoom.streamer.name" class="streamer-avatar" />
            <div class="streamer-details">
              <div class="streamer-name">{{ liveRoom.streamer.name }}</div>
              <div class="streamer-fans">粉丝 {{ formatViewerCount(liveRoom.streamer.fans) }}</div>
            </div>
            <el-button 
              v-if="!isFollowing" 
              type="primary" 
              @click="followStreamer"
              class="follow-btn"
            >
              关注
            </el-button>
            <el-button 
              v-else 
              type="default" 
              @click="unfollowStreamer"
              class="followed-btn"
            >
              已关注
            </el-button>
          </div>
          
          <div class="live-meta">
            <span class="live-category">{{ liveRoom.category }}</span>
            <span class="live-start-time">开播时间: {{ formatStartTime(liveRoom.startTime) }}</span>
          </div>
        </div>
      </div>
      
      <!-- 聊天和弹幕区域 -->
      <div class="live-interaction-section">
        <!-- 弹幕输入 -->
        <div class="danmaku-input-section">
          <el-input
            v-model="danmakuContent"
            placeholder="发送弹幕..."
            suffix-icon="el-icon-send"
            @keyup.enter.native="sendDanmaku"
            clearable
          />
          <el-color-picker v-model="danmakuColor" class="danmaku-color-picker" />
        </div>
        
        <!-- 弹幕列表 -->
        <div class="danmaku-list" ref="danmakuContainer">
          <div 
            v-for="(danmaku, index) in danmakus" 
            :key="index"
            class="danmaku-item"
            :style="{ color: danmaku.color, animationDuration: `${5 + Math.random() * 5}s` }"
          >
            {{ danmaku.content }}
          </div>
        </div>
      </div>
      
      <!-- 推荐直播间 -->
      <div class="recommended-lives">
        <h3>推荐直播</h3>
        <div class="recommended-list">
          <div 
            v-for="room in recommendedRooms" 
            :key="room.id" 
            class="recommended-item"
            @click="goToRoom(room.id)"
          >
            <div class="recommended-cover">
              <img :src="room.cover" :alt="room.title" />
              <span class="recommended-viewers">{{ formatViewerCount(room.viewers) }}</span>
            </div>
            <div class="recommended-info">
              <div class="recommended-title">{{ room.title }}</div>
              <div class="recommended-streamer">{{ room.streamer.name }}</div>
            </div>
          </div>
        </div>
      </div>
    </template>
    
    <div v-else class="error-container">
      <el-empty description="直播间不存在或已关闭" />
      <el-button type="primary" @click="goBack">返回直播间列表</el-button>
    </div>
  </div>
</template>

<script>
import { liveService, authService } from '../services'
import videojs from 'video.js'

export default {
  name: 'LiveRoomView',
  data() {
    return {
      liveRoom: null,
      liveStreamUrl: '',
      recommendedRooms: [],
      danmakus: [],
      danmakuContent: '',
      danmakuColor: '#FFFFFF',
      loading: true,
      isFollowing: false,
      videoPlayer: null,
      currentUserId: null
    }
  },
  async mounted() {
    // 获取当前用户信息
    const user = authService.getCurrentUser()
    this.currentUserId = user?.id
    
    // 加载直播间信息
    await this.fetchLiveRoomDetail()
    await this.fetchRecommendedRooms()
    
    // 开始接收弹幕
    this.startDanmakuListener()
  },
  beforeUnmount() {
    // 清理视频播放器
    if (this.videoPlayer) {
      this.videoPlayer.dispose()
    }
    
    // 停止弹幕监听
    if (this.danmakuInterval) {
      clearInterval(this.danmakuInterval)
    }
  },
  methods: {
    async fetchLiveRoomDetail() {
      try {
        const roomId = this.$route.params.id
        this.liveRoom = await liveService.getLiveRoomDetail(roomId)
        this.liveStreamUrl = await liveService.getLiveStreamUrl(roomId)
        
        // 检查是否已关注
        if (this.currentUserId) {
          this.isFollowing = await liveService.checkFollowStatus(this.currentUserId, this.liveRoom.streamer.id)
        }
      } catch (error) {
        this.$message.error('获取直播间信息失败')
      } finally {
        this.loading = false
      }
    },
    
    async fetchRecommendedRooms() {
      try {
        const result = await liveService.getLiveRoomsByCategory(this.liveRoom?.category || null, 1, 5)
        this.recommendedRooms = result.rooms.filter(room => room.id !== this.liveRoom?.id)
      } catch (error) {
        console.error('获取推荐直播间失败', error)
      }
    },
    
    async sendDanmaku() {
      if (!this.danmakuContent.trim()) return
      
      if (!this.currentUserId) {
        this.$message.warning('请先登录后发送弹幕')
        return
      }
      
      try {
        await liveService.sendDanmaku({
          roomId: this.$route.params.id,
          content: this.danmakuContent,
          color: this.danmakuColor,
          userId: this.currentUserId
        })
        
        // 清空输入
        this.danmakuContent = ''
      } catch (error) {
        this.$message.error('发送弹幕失败')
      }
    },
    
    startDanmakuListener() {
      // 模拟实时接收弹幕
      this.danmakuInterval = setInterval(async () => {
        try {
          const newDanmakus = await liveService.getDanmakus(this.$route.params.id, 1, 10)
          if (newDanmakus.length > 0) {
            // 添加新弹幕
            newDanmakus.forEach(danmaku => {
              if (!this.danmakus.some(d => d.id === danmaku.id)) {
                this.danmakus.push(danmaku)
                // 保持弹幕数量在合理范围
                if (this.danmakus.length > 100) {
                  this.danmakus.shift()
                }
              }
            })
          }
        } catch (error) {
          console.error('获取弹幕失败', error)
        }
      }, 3000)
    },
    
    async followStreamer() {
      if (!this.currentUserId) {
        this.$message.warning('请先登录')
        return
      }
      
      try {
        await liveService.followStreamer(this.currentUserId, this.liveRoom.streamer.id)
        this.isFollowing = true
        this.$message.success('关注成功')
      } catch (error) {
        this.$message.error('关注失败')
      }
    },
    
    async unfollowStreamer() {
      try {
        await liveService.unfollowStreamer(this.currentUserId, this.liveRoom.streamer.id)
        this.isFollowing = false
        this.$message.success('取消关注成功')
      } catch (error) {
        this.$message.error('取消关注失败')
      }
    },
    
    goToRoom(roomId) {
      this.$router.push(`/live/${roomId}`)
    },
    
    goBack() {
      this.$router.push('/live')
    },
    
    formatViewerCount(viewers) {
      if (viewers >= 10000) {
        return (viewers / 10000).toFixed(1) + '万'
      }
      return viewers
    },
    
    formatStartTime(startTime) {
      return new Date(startTime).toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
.live-room-view {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.loading-container, .error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
}

.live-player-section {
  margin-bottom: 30px;
}

.live-player {
  position: relative;
  padding-top: 56.25%;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
}

.live-video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.live-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.live-status {
  position: absolute;
  top: 10px;
  left: 10px;
}

.live-badge {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  padding: 4px 8px;
  background: rgba(255, 0, 0, 0.8);
  color: white;
  border-radius: 4px;
  font-size: 14px;
}

.live-dot {
  width: 8px;
  height: 8px;
  background: white;
  border-radius: 50%;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

.offline-badge {
  padding: 4px 8px;
  background: rgba(100, 100, 100, 0.8);
  color: white;
  border-radius: 4px;
  font-size: 14px;
}

.viewer-stats {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 4px 8px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  border-radius: 4px;
  font-size: 14px;
}

.live-info-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.live-title {
  font-size: 24px;
  margin-bottom: 15px;
  color: #333;
}

.streamer-info {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
}

.streamer-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  border: 2px solid #e6f7ff;
}

.streamer-details {
  flex: 1;
}

.streamer-name {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 5px;
}

.streamer-fans {
  font-size: 14px;
  color: #666;
}

.follow-btn, .followed-btn {
  min-width: 100px;
}

.live-meta {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #666;
}

.live-category {
  padding: 4px 12px;
  background: #e6f7ff;
  color: #1890ff;
  border-radius: 4px;
}

.live-interaction-section {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
}

.danmaku-input-section {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.danmaku-color-picker {
  margin-top: 10px;
}

.danmaku-list {
  flex: 2;
  background: #1a1a1a;
  border-radius: 8px;
  height: 400px;
  overflow: hidden;
  position: relative;
}

.danmaku-item {
  position: absolute;
  white-space: nowrap;
  font-size: 16px;
  line-height: 1.5;
  text-shadow: 0 0 2px rgba(0, 0, 0, 0.8);
  animation: scrollDanmaku linear infinite;
}

@keyframes scrollDanmaku {
  from {
    transform: translateX(100%);
  }
  to {
    transform: translateX(-100%);
  }
}

.recommended-lives {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.recommended-lives h3 {
  margin-bottom: 15px;
  font-size: 18px;
  color: #333;
}

.recommended-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
}

.recommended-item {
  cursor: pointer;
  transition: transform 0.2s;
}

.recommended-item:hover {
  transform: translateY(-3px);
}

.recommended-cover {
  position: relative;
  padding-top: 56.25%;
  margin-bottom: 10px;
}

.recommended-cover img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.recommended-viewers {
  position: absolute;
  bottom: 5px;
  right: 5px;
  padding: 2px 6px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  font-size: 12px;
  border-radius: 3px;
}

.recommended-title {
  font-size: 14px;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.recommended-streamer {
  font-size: 12px;
  color: #666;
}

@media (max-width: 768px) {
  .live-interaction-section {
    flex-direction: column;
  }
  
  .live-title {
    font-size: 20px;
  }
  
  .streamer-info {
    flex-wrap: wrap;
  }
}
</style>